<!--
 * @Author: 瞿旺兴 18774621495@163.com
 * @Date: 2022-05-31 19:48:10
 * @LastEditors: 瞿旺兴 18774621495@163.com
 * @LastEditTime: 2022-06-06 17:28:40
 * @FilePath: \nien-vue3-admin\src\views\BusinessConfiguration\sellPriceManagement\components\PriceDetail.vue
 * @Description: 价格详情
-->
<template>
  <el-dialog v-model="visible" title="价格详情">
    <el-button
      type="primary"
      class="mb-12"
      :icon="Plus"
      @click="edit('新增')"
    >
      新增
    </el-button>
    <el-table v-loading="loading" :data="tableData">
      <el-table-column
        label="收货站点"
        align="center"
        :formatter="resetReceivingSite"
        prop="receivingSite"
      ></el-table-column>
      <el-table-column label="状态">
        <template #default="{row}">
          <el-switch
            :value="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="val => handelChangeSwitch(row, val)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="生效日期" align="center" prop="effectiveDate"></el-table-column>
      <el-table-column label="失效日期" align="center" prop="expirationDate"></el-table-column>
      <el-table-column label="备注" align="center" prop="remarks"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{row}">
          <el-button type="primary" text @click="edit('修改', row)">修改</el-button>
          <el-divider direction="vertical" class="divider-margin"></el-divider>
          <el-button type="primary" text @click="editDelete(row.id)">删除</el-button>
          <el-divider direction="vertical" class="divider-margin"></el-divider>
          <el-button type="primary" text @click="priceManage(row)">价格管理</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
  <!-- 修改、新增 -->
  <el-dialog
    v-model="editVisible" 
    :before-close="editCancel"
    :title="`${editTitle}价格管理`"
    width="600px"
  >
    <el-form
      ref="editFormRef"
      :model="editForm"
      :rules="rules"
      label-position="top"
    >
      <el-row :gutter="28">
        <el-col :span="12">
          <el-form-item label="收货站点" prop="receivingSite">
            <el-select
              v-model="editForm.receivingSite"
              multiple
            >
              <el-option 
                v-for="dict in dicts[DictDirection.收货站点]"
                :key="dict.deptId"
                :label="dict.deptName"
                :value="dict.deptId + ''"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生效日期" prop="effectiveDate">
            <el-date-picker 
              v-model="editForm.effectiveDate"
              type="datetime"
              value-format="YYYY-MM-DD hh:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="失效日期" prop="expirationDate">
            <el-date-picker
              v-model="editForm.expirationDate"
              type="datetime"
              value-format="YYYY-MM-DD hh:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="editForm.remarks" type="textarea" rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="info" @click="editCancel">取消</el-button>
      <el-button type="primary" :loading="editLoading" @click="editConfirm">确定</el-button>
    </template>
  </el-dialog>
  <!-- 价格管理 -->
  <edit-price-management ref="editPriceManagementRef" :site-id="sellingPriceId" />
</template>

<script setup lang="ts">
import { ref, defineExpose, defineAsyncComponent, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { 
  selectSellingPriceSiteList,
  sellingPriceSiteAdd,
  sellingPriceSiteEdit,
  sellingPriceSiteRemove,
  sellingPriceSiteEditStatus } from '@/api/BusinessConfig/sellPriceManagement'
import useDicts, { DictDirection } from '@/store/modules/dicts'

import { validateForm, depClone } from '@/utils'

const dicts = useDicts()
dicts.setDicts(DictDirection.收货站点)
const EditPriceManagement = defineAsyncComponent(() => import('./EditPriceManagement.vue'))

const editPriceManagementRef = ref()

const visible = ref<boolean>(false)
const loading = ref<boolean>(false)
const sellingPriceId = ref()
const tableData = ref([])

const getList = () => {
  loading.value = true
  selectSellingPriceSiteList({ sellingPriceId: sellingPriceId.value }).then(({ code, data }) => {
    if (code === 200) {
      tableData.value = data
    }
  }).finally(() => {
    loading.value = false
  })
}

const resetReceivingSite = (row) => {
  const res = []
  if (Array.isArray(row.receivingSite)) {
    row.receivingSite.forEach(el => {
      const dept = dicts[DictDirection.收货站点].filter(site => el == site.deptId)
      res.push(dept[0]?.deptName)
    })
  }
  return res.join(',')
}
const priceManage = (row) => {
  editPriceManagementRef.value.open(row.id)
}

// ------------编辑
const editTitle = ref<string>('修改')
const editVisible = ref<boolean>(false)
const editLoading = ref<boolean>(false)
const editFormRef = ref()
const editForm = ref({
  receivingSite: [],
  effectiveDate: '',
  expirationDate: '',
  remarks: '',
})
const rules = {
  receivingSite: [{ required: true, message: '请选择收货站点', trigger: 'change' }],
  effectiveDate: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
  expirationDate: [{ required: true, message: '请选择失效日期', trigger: 'change' }],
}
const editDelete = (id) => {
  ElMessageBox.confirm('是否删除当前项？').then(() => {
    sellingPriceSiteRemove(id).then(({ code }) => {
      if (code === 200) {
        ElMessage.success('删除成功！')
        getList()
      }
    })
  })
}
const handelChangeSwitch = (row, val) => {
  ElMessageBox.confirm('是否修改当前状态？').then(() => {
    const data = {
      id: row.id,
      status: val,
    }
    sellingPriceSiteEditStatus(data).then(({ code }) => {
      if (code === 200) {
        ElMessage.success('修改成功')
        row.status = val
      }
    })
  })
}
const edit = (type:string, row?) => {
  editTitle.value = type
  editVisible.value = true
  if (type === '修改') {
    editForm.value = depClone(row)
  }
  nextTick(() => {
    editFormRef.value && editFormRef.value.resetFields()
  })
}

const editConfirm = () => {
  validateForm(editFormRef.value, () => {
    const fn = editTitle.value === '修改' ? sellingPriceSiteEdit : sellingPriceSiteAdd
    editLoading.value = true
    const params = { ...editForm.value, 
      receivingSiteStr: editForm.value.receivingSite.join(','),
      sellingPriceId: sellingPriceId.value,
    }
    fn(params).then(({ code }) => {
      if (code === 200) {
        ElMessage.success(`${ editTitle.value }成功！`)
        editCancel()
        getList()
      }
    }).finally(() => {
      editLoading.value = false
    })
  })
}
const editCancel = () => {
  editForm.value = {
    receivingSite: [],
    effectiveDate: '',
    expirationDate: '',
    remarks: '',
  }
  editVisible.value = false
}

const open = (id) => {
  sellingPriceId.value = id
  getList()
  visible.value = true
}

defineExpose({
  open,
})
</script>

<style lang="less" scoped>
.mb-12{
  margin-bottom: 12px;
}
.divider-margin{
  margin: 0;
}
</style>